<template>
  <div id="mapView" class="map-view">
    <!-- 图层控制面板 -->
    <div class="layer-control-panel">
      <el-card class="layer-card">
        <el-collapse v-model="activeCollapse">
          <el-collapse-item title="图层显示控制" name="layers">
            <el-space direction="vertical" alignment="stretch" size="small">
              <el-checkbox
                v-model="layerVisibility.maintenance"
                @change="toggleLayerVisibility('maintenance')"
              >
                维修站点
              </el-checkbox>
            </el-space>
          </el-collapse-item>
          <el-collapse-item title="图层操作控制" name="operations">
            <el-space direction="vertical" alignment="stretch" size="small">
              <el-button type="primary" @click="startAddMaintenance" :disabled="isDrawing">
                <el-icon><Plus /></el-icon> 新增维修站点
              </el-button>
            </el-space>
          </el-collapse-item>
        </el-collapse>
      </el-card>
    </div>

    <!-- 维修站点属性表单对话框 -->
    <el-dialog
      v-model="maintenanceFormVisible"
      :title="formMode === 'add' ? '新增维修站点' : '编辑维修站点'"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        :model="maintenanceForm"
        label-width="120px"
        :rules="maintenanceFormRules"
        ref="maintenanceFormRef"
      >
        <el-form-item label="站点名称" prop="maintenanceName">
          <el-input
            v-model="maintenanceForm.maintenanceName"
            placeholder="请输入站点名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="站点地址" prop="maintenanceAddress">
          <el-input
            v-model="maintenanceForm.maintenanceAddress"
            placeholder="请输入站点地址"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelMaintenanceForm">取消</el-button>
          <el-button type="primary" @click="submitMaintenanceForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 维修站点属性查看对话框 -->
    <el-dialog
      v-model="maintenanceInfoVisible"
      title="维修站点信息"
      width="500px"
      :key="refreshMaintenanceKey"
    >
      <div v-if="selectedMaintenance">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="站点名称">
            {{ selectedMaintenance.attributes.maintenanceName }}
          </el-descriptions-item>
          <el-descriptions-item label="站点地址">
            {{ selectedMaintenance.attributes.maintenanceAddress }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="maintenanceInfoVisible = false">关闭</el-button>
          <el-button type="primary" @click="editMaintenance">编辑</el-button>
          <el-button type="danger" @click="confirmDeleteMaintenance">删除</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog v-model="deleteConfirmVisible" title="确认删除" width="300px">
      <p>确定要删除该维修站点吗？此操作不可恢复。</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteConfirmVisible = false">取消</el-button>
          <el-button type="danger" @click="deleteMaintenance">确定删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref, reactive, nextTick } from 'vue'
import { ElMessage, ElForm } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import Map from '@arcgis/core/Map.js'
import MapView from '@arcgis/core/views/MapView.js'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer.js'
import Graphic from '@arcgis/core/Graphic.js'
import GraphicsLayer from '@arcgis/core/layers/GraphicsLayer.js'
import SketchViewModel from '@arcgis/core/widgets/Sketch/SketchViewModel.js'
import SimpleMarkerSymbol from '@arcgis/core/symbols/SimpleMarkerSymbol.js'
import Query from '@arcgis/core/rest/support/Query.js'
import gaodeLayer from '../utils/GaoDeBaseLayer'
import PictureMarkerSymbol from '@arcgis/core/symbols/PictureMarkerSymbol'
import sign from '@/assets/sign.png'
import maintenance from '@/assets/maintenance.png'

let view: MapView | null = null
let maintenanceLayer: FeatureLayer | null = null
let signLayer: FeatureLayer | null = null
let highwayLineLayer: FeatureLayer | null = null
let sketchLayer: GraphicsLayer | null = null
let sketchViewModel: SketchViewModel | null = null
let tempGraphic: Graphic | null = null

// 图层可见性控制
const layerVisibility = ref({
  maintenance: true,
}) as any

// 控制折叠面板的展开状态
const activeCollapse = ref(['layers', 'operations'])
// 添加一个刷新标记
const refreshMaintenanceKey = ref(0)

// 表单相关
const maintenanceFormRef = ref<InstanceType<typeof ElForm> | null>(null)
const maintenanceFormVisible = ref(false)
const formMode = ref<'add' | 'edit'>('add')
const isDrawing = ref(false)
const maintenanceInfoVisible = ref(false)
const deleteConfirmVisible = ref(false)
let selectedMaintenance: Graphic | null = null

// 维修站点表单数据
const maintenanceForm = reactive({
  maintenanceName: '',
  maintenanceAddress: '',
})

// 维修站点表单验证规则
const maintenanceFormRules = {
  maintenanceName: [{ required: true, message: '请输入站点名称', trigger: 'blur' }],
  maintenanceAddress: [{ required: true, message: '请输入站点地址', trigger: 'blur' }],
}

// 切换图层可见性
const toggleLayerVisibility = (layerType: string) => {
  if (layerType === 'maintenance' && maintenanceLayer) {
    maintenanceLayer.visible = Boolean(layerVisibility.value.maintenance)
  }
}

// 开始添加维修站点
const startAddMaintenance = () => {
  if (!view || !sketchViewModel) return

  isDrawing.value = true
  ElMessage.info('请在地图上点击添加维修站点位置')

  // 开始绘制点
  sketchViewModel.create('point')
}

// 取消维修站点表单
const cancelMaintenanceForm = () => {
  maintenanceFormVisible.value = false
  resetMaintenanceForm()

  // 如果是添加模式，清除临时图形
  if (formMode.value === 'add' && tempGraphic && sketchLayer) {
    sketchLayer.remove(tempGraphic)
    tempGraphic = null
  }

  isDrawing.value = false
}

// 重置维修站点表单
const resetMaintenanceForm = () => {
  if (maintenanceFormRef.value) {
    maintenanceFormRef.value.resetFields()
  }

  maintenanceForm.maintenanceName = ''
  maintenanceForm.maintenanceAddress = ''
}

// 提交维修站点表单
const submitMaintenanceForm = async () => {
  if (!maintenanceFormRef.value) return

  await maintenanceFormRef.value.validate(async (valid) => {
    if (valid) {
      if (formMode.value === 'add') {
        // 添加新维修站点
        addMaintenance()
      } else {
        // 更新维修站点
        updateMaintenance()
      }
    }
  })
}

// 添加新维修站点
const addMaintenance = () => {
  if (!tempGraphic || !maintenanceLayer) return

  // 创建新的维修站点图形
  const attributes = {
    maintenanceName: maintenanceForm.maintenanceName,
    maintenanceAddress: maintenanceForm.maintenanceAddress,
  }

  // 创建新的图形
  const newGraphic = new Graphic({
    geometry: tempGraphic.geometry,
    attributes: attributes,
  })

  // 添加到图层
  maintenanceLayer
    .applyEdits({
      addFeatures: [newGraphic],
    })
    .then((result) => {
      if (result.addFeatureResults.length > 0) {
        ElMessage.success('维修站点添加成功')
        maintenanceFormVisible.value = false
        resetMaintenanceForm()

        // 清除临时图形
        if (sketchLayer && tempGraphic) {
          sketchLayer.removeAll()
          tempGraphic = null
        }

        isDrawing.value = false
      } else {
        ElMessage.error('维修站点添加失败')
      }
    })
    .catch((error) => {
      console.error('添加维修站点出错:', error)
      ElMessage.error('维修站点添加失败')
    })
}

// 编辑维修站点
const editMaintenance = () => {
  if (!selectedMaintenance) return

  formMode.value = 'edit'

  // 填充表单数据
  const attrs = selectedMaintenance.attributes
  maintenanceForm.maintenanceName = attrs.maintenanceName || ''
  maintenanceForm.maintenanceAddress = attrs.maintenanceAddress || ''

  maintenanceInfoVisible.value = false
  maintenanceFormVisible.value = true
}

// 更新维修站点
const updateMaintenance = () => {
  if (!selectedMaintenance || !maintenanceLayer) return

  // 更新属性
  const updatedGraphic = selectedMaintenance.clone()
  updatedGraphic.attributes.maintenanceName = maintenanceForm.maintenanceName
  updatedGraphic.attributes.maintenanceAddress = maintenanceForm.maintenanceAddress

  // 应用编辑
  maintenanceLayer
    .applyEdits({
      updateFeatures: [updatedGraphic],
    })
    .then((result) => {
      if (result.updateFeatureResults.length > 0) {
        ElMessage.success('维修站点更新成功')
        maintenanceFormVisible.value = false
        resetMaintenanceForm()
        // 强制刷新组件
        nextTick(() => {
          refreshMaintenanceKey.value++
        })
      } else {
        ElMessage.error('维修站点更新失败')
      }
    })
    .catch((error) => {
      console.error('更新维修站点出错:', error)
      ElMessage.error('维修站点更新失败')
    })
}

// 确认删除维修站点
const confirmDeleteMaintenance = () => {
  deleteConfirmVisible.value = true
}

// 删除维修站点
const deleteMaintenance = () => {
  if (!selectedMaintenance || !maintenanceLayer) return

  maintenanceLayer
    .applyEdits({
      deleteFeatures: [selectedMaintenance],
    })
    .then((result) => {
      if (result.deleteFeatureResults.length > 0) {
        ElMessage.success('维修站点删除成功')
        maintenanceInfoVisible.value = false
        deleteConfirmVisible.value = false
        selectedMaintenance = null
      } else {
        ElMessage.error('维修站点删除失败')
      }
    })
    .catch((error) => {
      console.error('删除维修站点出错:', error)
      ElMessage.error('维修站点删除失败')
    })
}

// 初始化地图
onMounted(() => {
  // 创建维修站点图层
  maintenanceLayer = new FeatureLayer({
    url: 'https://services6.arcgis.com/aSAH0FbO8tv30xLs/arcgis/rest/services/maintenance/FeatureServer/0',
    outFields: ['*'],
    renderer: {
      type: 'simple',
      symbol: new PictureMarkerSymbol({
        url: maintenance,
        width: 24,
        height: 24,
      }),
    },
    popupEnabled: false,
    popupTemplate: {
      title: '维修站点信息',
      content: [
        {
          type: 'fields',
          fieldInfos: [
            {
              fieldName: 'maintenanceName',
              label: '站点名称',
            },
            {
              fieldName: 'maintenanceAddress',
              label: '站点地址',
            },
          ],
        },
      ],
    },
  })
  // 创建标志牌图层
  signLayer = new FeatureLayer({
    url: 'https://services6.arcgis.com/aSAH0FbO8tv30xLs/arcgis/rest/services/HighwayManagementSystem/FeatureServer/2',
    title: '标志牌',
    outFields: ['*'],
    renderer: {
      type: 'simple',
      symbol: new PictureMarkerSymbol({
        url: sign,
        width: 24,
        height: 24,
      }),
    },
    popupTemplate: {
      title: '标志牌信息',
      content: [
        {
          type: 'fields',
          fieldInfos: [
            { fieldName: 'SignType', label: '标志类型' },
            { fieldName: 'Content', label: '内容' },
            { fieldName: 'InstallationDate', label: '安装日期' },
            { fieldName: 'BoardSize', label: '尺寸' },
            { fieldName: 'Material', label: '材质' },
            { fieldName: 'Status', label: '状态' },
            { fieldName: 'LastInspectionDate', label: '最后检查日期' },
            { fieldName: 'RoadSegmentID', label: '路段ID' },
            { fieldName: 'ExpectedLifespan', label: '预期寿命' },
            { fieldName: 'MaintenanceDate', label: '维护日期' },
            { fieldName: 'MaintenanceType', label: '维护类型' },
            { fieldName: 'Description', label: '描述' },
          ],
        },
      ],
    },
  })

  // 创建高速公路线图层
  highwayLineLayer = new FeatureLayer({
    url: 'https://services6.arcgis.com/aSAH0FbO8tv30xLs/arcgis/rest/services/HighwayManagementSystem/FeatureServer/3',
    title: '高速公路',
    outFields: ['*'],

    popupTemplate: {
      title: '高速公路信息',
      content: [
        {
          type: 'fields',
          fieldInfos: [
            { fieldName: 'RoadName', label: '道路名称' },
            { fieldName: 'StartPoint', label: '起点' },
            { fieldName: 'EndPoint', label: '终点' },
            { fieldName: 'LaneCount', label: '车道数' },
            { fieldName: 'DesignSpeed', label: '设计时速(km/h)' },
            { fieldName: 'OpenDate', label: '开通日期' },
            { fieldName: 'AdminRegion', label: '行政区域' },
          ],
        },
      ],
    },
  })
  // 创建地图
  const map = new Map({
    basemap: {
      baseLayers: [gaodeLayer],
    },
    layers: [maintenanceLayer, highwayLineLayer, signLayer],
  })

  // 创建地图视图
  view = new MapView({
    container: 'mapView',
    map: map,
    center: [116.7461293, 36.5598627],
    zoom: 12,
  })

  // 创建绘图图层
  sketchLayer = new GraphicsLayer()
  map.add(sketchLayer)

  // 创建绘图工具
  sketchViewModel = new SketchViewModel({
    view: view,
    layer: sketchLayer,
  })

  view.on('click', (event) => {
    if (isDrawing.value) return

    // 查询维修站点
    const query = new Query({
      geometry: event.mapPoint,
      distance: 100,
      units: 'meters',
      outFields: ['*'],
      returnGeometry: true,
      where: '1=1', // 查询所有要素
    })

    maintenanceLayer!.queryFeatures(query).then((results) => {
      if (results.features.length > 0) {
        selectedMaintenance = results.features[0]
        maintenanceInfoVisible.value = true
        // 强制刷新组件
        nextTick(() => {
          refreshMaintenanceKey.value++
        })
      }
    })
  })

  // 监听绘图完成事件
  sketchViewModel.on('create', (event) => {
    if (event.state === 'complete') {
      tempGraphic = event.graphic
      maintenanceFormVisible.value = true
      isDrawing.value = false
    }
  })
})

// 清理资源
onUnmounted(() => {
  if (view) {
    view = null
  }
})
</script>

<style scoped>
.map-view {
  width: 100%;
  height: 100%;
  position: relative;
}

.layer-control-panel {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 1;
  width: 300px;
}

.layer-card {
  background-color: rgba(255, 255, 255, 0.9);
}
</style>
